import { ref } from 'vue'

let lockCount = 0
const originalOverflow = ref('')
const originalPaddingRight = ref('')

export function useLockScroll() {
  const lock = () => {
    if (lockCount === 0) {
      // 保存原始样式
      originalOverflow.value = document.body.style.overflow
      originalPaddingRight.value = document.body.style.paddingRight
      
      // 获取滚动条宽度
      const scrollBarWidth = window.innerWidth - document.documentElement.clientWidth
      
      // 应用锁定样式
      document.body.style.overflow = 'hidden'
      if (scrollBarWidth > 0) {
        document.body.style.paddingRight = `${scrollBarWidth}px`
      }
    }
    lockCount++
  }

  const unlock = () => {
    if (lockCount <= 0) return
    
    lockCount--
    
    if (lockCount === 0) {
      // 恢复原始样式
      document.body.style.overflow = originalOverflow.value
      document.body.style.paddingRight = originalPaddingRight.value
    }
  }

  return {
    lock,
    unlock
  }
}